package com.sense.kukoo.biz_explore.view

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.sense.kukoo.biz_explore.R
import com.sense.kukoo.biz_explore.adapter.IndexContentAdapter
import com.sense.kukoo.biz_explore.databinding.BizExploreFragmentContent2Binding
import com.sense.kukoo.biz_explore.vm.Content2ViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.constant.ConstantConfig
import com.sense.kukoo.common.listener.OnScrollYChangedListener
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.view.BaseMvvmFragment
import com.sense.kukoo.common.repo.http.bean.IndexContentBean
import com.sense.kukoo.common.repo.http.bean.ModuleBean
import com.sense.kukoo.common.wiget.state.NetworkErrorState
import com.zy.multistatepage.state.SuccessState

class Content2Fragment : BaseMvvmFragment<Content2ViewModel, BizExploreFragmentContent2Binding>() {

    private val TAG: String = javaClass.simpleName
    private lateinit var mModuleBean: ModuleBean
    private lateinit var mAdapter:IndexContentAdapter

    private var mOnScrollYChangedListener: OnScrollYChangedListener? = null
    private var explorePosition: Int = 0

    var mCurrentMusic: LocalMediaListItemBean? = null
    var mCurrentPlayState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            mModuleBean = it.getParcelable(ConstantConfig.ARG1)!!
        }
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: ModuleBean) =
            Content2Fragment().apply {
                arguments = Bundle().apply {
                    putParcelable(ConstantConfig.ARG1, param1)
                }
            }
    }

    override fun getLayout(): Int = R.layout.biz_explore_fragment_content2

    override fun getViewModelClass(): Class<Content2ViewModel> = Content2ViewModel::class.java

    override fun createViewModel(clazz: Class<Content2ViewModel>): Content2ViewModel {
        return ViewModelProvider(requireActivity()).get("" + mModuleBean.id, clazz)
    }

    override fun initParam() {}

    override fun responseVM(action: Int) {}

    @SuppressLint("NotifyDataSetChanged")
    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        bindAction(mViewModel.action_finishRefresh){
            mBinding.refreshLayout.finishRefresh()
        }
        bindAction(mViewModel.action_finishLoadMore){
            mBinding.refreshLayout.finishLoadMore()
        }
        bindAction(mViewModel.action_networkError){
            mBinding.multiStateContainer.show<NetworkErrorState> {
                it.onRetry {
                    mViewModel.onErrorRetry()
                }
            }
        }
        bindData(mViewModel.data_content){
            mBinding.multiStateContainer.show<SuccessState>()
            mAdapter.list = it
            mAdapter.notifyDataSetChanged()
        }
        bindData(mViewModel.data_enableLoadMore){
            mBinding.refreshLayout.setEnableLoadMore(it)
        }
    }

    override fun initView() {
        mAdapter = IndexContentAdapter(mutableListOf(), mListener)
        mBinding.recyclerView.adapter = mAdapter

        val linearLayoutManager = LinearLayoutManager(context)
        mBinding.recyclerView.layoutManager = linearLayoutManager
        mBinding.refreshLayout.setOnRefreshListener {
            //OnRefresh
            mViewModel.refreshData()
        }
        mBinding.refreshLayout.setOnLoadMoreListener {
            //OnLoadMore
            mViewModel.loadMoreData()
        }
        //
        mBinding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            private var isScroll = false

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                if (isScroll) {
                    mOnScrollYChangedListener?.onChanged(0, explorePosition, dy, RecyclerView.SCROLL_STATE_DRAGGING)
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if(newState == RecyclerView.SCROLL_STATE_IDLE){
                    isScroll = false
                    mOnScrollYChangedListener?.onChanged(0, explorePosition, 0, RecyclerView.SCROLL_STATE_IDLE)
                } else {
                    isScroll = true
                }
            }
        })
    }

    override fun singleLazyLoad() {
        mViewModel.setData(mModuleBean)
        mBinding.refreshLayout.autoRefresh()
    }

    fun setOnScrollYChangedListener(explorePosition: Int, l: OnScrollYChangedListener){
        this.explorePosition = explorePosition
        mOnScrollYChangedListener = l
    }

    private val mListener = object :IndexContentAdapter.IndexContentEventListener{
        override fun onItemClick(data: IndexContentBean) {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_DESCRIPTION_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${data.id}")
                .navigation()
        }

        override fun onChannelClick(data: IndexContentBean) {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_CHANNEL_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${data.userId}")
                .navigation()
        }

        override fun onBtnPlayClick(data: IndexContentBean) {
            if(mCurrentMusic?.idOfChapter() == data.id){
                //当前的
                when (mCurrentPlayState) {
                    UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                    UserWatcher.MusicStateWatcher.STATE_SEEKING,
                    UserWatcher.MusicStateWatcher.STATE_PREPARE,
                    UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                        Kukoo.input.pause()
                    }
                    /*UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING ->{}
                    UserWatcher.MusicStateWatcher.STATE_PAUSE ->{}*/
                    else -> {
                        Kukoo.input.start()
                    }
                }
            }else{
                //非当前的
                Kukoo.input.play(LocalMediaListItemBean(data))
            }
        }
    }

    private val mWatcher = object: UserWatcher.MusicStateWatcher{

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            mCurrentMusic = music
            mAdapter.setCurrentMusic(music)
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {}

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(state: Int) {
            mCurrentPlayState = state
            mAdapter.setCurrentPlayState(state)
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Kukoo.watcher.register(mWatcher)
    }

    override fun onDestroy() {
        super.onDestroy()
        Kukoo.watcher.unregister(mWatcher)
    }

}